"""
MCP工具管理路由
"""

from typing import Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from config.database import get_db_session
from config.logging_config import get_logger
from mcp_tools.mcpManager import mcp_manager
from pojo.ai_web_detail_tools import (
    AIWebDetailToolsResponse,
    AIWebDetailToolsListResponse,
    AIWebDetailToolsUpdate,
    AIWebDetailToolsStatusUpdate,
    AIWebDetailToolsInteractiveUpdate
)
from pojo.ai_web_detail_tools_model import AIWebDetailToolsModel
from pojo.ai_web_mcp_tools import (
    AIWebMCPToolsCreate,
    AIWebMCPToolsUpdate,
    AIWebMCPToolsResponse,
    AIWebMCPToolsListResponse,
    AIWebMCPToolsStatusUpdate
)
from pojo.ai_web_mcp_tools_model import AIWebMCPToolsModel

router = APIRouter()
logger = get_logger(__name__)


@router.get("/list", response_model=AIWebMCPToolsListResponse, summary="获取MCP工具列表")
async def get_mcp_tools(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        mcp_name: Optional[str] = Query(None, description="MCP工具名称模糊查询"),
        status: Optional[int] = Query(None, description="状态筛选"),
        access_type: Optional[int] = Query(None, description="接入类型筛选"),
        db: Session = Depends(get_db_session)
):
    """获取MCP工具列表"""
    try:
        # 构建查询
        query = db.query(AIWebMCPToolsModel)

        # 添加筛选条件
        if mcp_name:
            query = query.filter(AIWebMCPToolsModel.mcp_name.like(f"%{mcp_name}%"))
        if status is not None:
            query = query.filter(AIWebMCPToolsModel.status == status)
        if access_type is not None:
            query = query.filter(AIWebMCPToolsModel.access_type == access_type)

        # 计算总数
        total = query.count()

        # 分页查询
        offset = (page - 1) * page_size
        items = query.order_by(AIWebMCPToolsModel.created_at.desc()).offset(offset).limit(page_size).all()

        # 转换为响应模型
        response_items = []
        for item in items:
            # 获取关联的工具详情数量 - 只统计MCP工具(tool_type=2)
            tools_count = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == item.id,
                AIWebDetailToolsModel.tool_type == 2
            ).count()

            enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == item.id,
                AIWebDetailToolsModel.tool_type == 2,
                AIWebDetailToolsModel.is_enabled == True
            ).count()

            item_dict = item.to_dict()
            item_dict['tools_count'] = tools_count
            item_dict['enabled_tools_count'] = enabled_tools_count
            item_dict['status_display'] = item.get_status_display()
            item_dict['access_type_display'] = item.get_access_type_display()

            response_items.append(AIWebMCPToolsResponse(**item_dict))

        return AIWebMCPToolsListResponse(total=total, items=response_items)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取MCP工具列表失败: {str(e)}")


@router.post("/create", response_model=AIWebMCPToolsResponse, summary="创建MCP工具")
async def create_mcp_tool(
        mcp_data: AIWebMCPToolsCreate,
        db: Session = Depends(get_db_session)
):
    """创建MCP工具"""
    try:
        # 检查名称是否重复
        existing = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.mcp_name == mcp_data.mcp_name
        ).first()

        if existing:
            raise HTTPException(status_code=400, detail="MCP工具名称已存在")

        # 创建新的MCP工具
        mcp_data_dict = mcp_data.model_dump(exclude={'id'})  # 排除ID字段，让数据库自动生成
        mcp_tool = AIWebMCPToolsModel(**mcp_data_dict)
        db.add(mcp_tool)
        db.commit()
        db.refresh(mcp_tool)

        # 返回响应
        result_dict = mcp_tool.to_dict()
        result_dict['tools_count'] = 0
        result_dict['enabled_tools_count'] = 0
        result_dict['status_display'] = mcp_tool.get_status_display()
        result_dict['access_type_display'] = mcp_tool.get_access_type_display()

        return AIWebMCPToolsResponse(**result_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建MCP工具失败: {str(e)}")


@router.put("/{mcp_id}", response_model=AIWebMCPToolsResponse, summary="更新MCP工具")
async def update_mcp_tool(
        mcp_id: str,
        mcp_data: AIWebMCPToolsUpdate,
        db: Session = Depends(get_db_session)
):
    """更新MCP工具"""
    try:
        # 查找MCP工具
        mcp_tool = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.id == mcp_id
        ).first()

        if not mcp_tool:
            raise HTTPException(status_code=404, detail="MCP工具不存在")

        # 检查名称重复（排除自身）
        if mcp_data.mcp_name:
            existing = db.query(AIWebMCPToolsModel).filter(
                AIWebMCPToolsModel.mcp_name == mcp_data.mcp_name,
                AIWebMCPToolsModel.id != mcp_id
            ).first()

            if existing:
                raise HTTPException(status_code=400, detail="MCP工具名称已存在")

        # 更新字段
        update_data = mcp_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(mcp_tool, field, value)

        db.commit()
        db.refresh(mcp_tool)

        # 获取工具统计 - 只统计MCP工具(tool_type=2)
        tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_tool.id,
            AIWebDetailToolsModel.tool_type == 2
        ).count()

        enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_tool.id,
            AIWebDetailToolsModel.tool_type == 2,
            AIWebDetailToolsModel.is_enabled == True
        ).count()

        # 返回响应
        result_dict = mcp_tool.to_dict()
        result_dict['tools_count'] = tools_count
        result_dict['enabled_tools_count'] = enabled_tools_count
        result_dict['status_display'] = mcp_tool.get_status_display()
        result_dict['access_type_display'] = mcp_tool.get_access_type_display()

        return AIWebMCPToolsResponse(**result_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新MCP工具失败: {str(e)}")


@router.delete("/{mcp_id}", summary="删除MCP工具")
async def delete_mcp_tool(
        mcp_id: str,
        db: Session = Depends(get_db_session)
):
    """删除MCP工具"""
    try:
        # 查找MCP工具
        mcp_tool = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.id == mcp_id
        ).first()

        if not mcp_tool:
            raise HTTPException(status_code=404, detail="MCP工具不存在")

        # 删除关联的工具详情
        db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_id
        ).delete()

        # 删除MCP工具
        db.delete(mcp_tool)
        db.commit()

        return {"message": "MCP工具删除成功"}

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除MCP工具失败: {str(e)}")


@router.put("/{mcp_id}/status", response_model=AIWebMCPToolsResponse, summary="更新MCP工具状态")
async def update_mcp_status(
        mcp_id: str,
        status_data: AIWebMCPToolsStatusUpdate,
        db: Session = Depends(get_db_session)
):
    """更新MCP工具状态"""
    try:
        # 查找MCP工具
        mcp_tool = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.id == mcp_id
        ).first()

        if not mcp_tool:
            raise HTTPException(status_code=404, detail="MCP工具不存在")

        # 更新状态
        mcp_tool.update_status(status_data.status)
        db.commit()
        db.refresh(mcp_tool)

        # 获取工具统计 - 只统计MCP工具(tool_type=2)
        tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_tool.id,
            AIWebDetailToolsModel.tool_type == 2
        ).count()

        enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_tool.id,
            AIWebDetailToolsModel.tool_type == 2,
            AIWebDetailToolsModel.is_enabled == True
        ).count()

        # 返回响应
        result_dict = mcp_tool.to_dict()
        result_dict['tools_count'] = tools_count
        result_dict['enabled_tools_count'] = enabled_tools_count
        result_dict['status_display'] = mcp_tool.get_status_display()
        result_dict['access_type_display'] = mcp_tool.get_access_type_display()

        return AIWebMCPToolsResponse(**result_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新MCP工具状态失败: {str(e)}")


@router.get("/{mcp_id}", response_model=AIWebMCPToolsResponse, summary="获取MCP工具详情")
async def get_mcp_tool(
        mcp_id: str,
        db: Session = Depends(get_db_session)
):
    """获取MCP工具详情"""
    try:
        # 查找MCP工具
        mcp_tool = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.id == mcp_id
        ).first()

        if not mcp_tool:
            raise HTTPException(status_code=404, detail="MCP工具不存在")

        # 获取工具统计 - 只统计MCP工具(tool_type=2)
        tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_tool.id,
            AIWebDetailToolsModel.tool_type == 2
        ).count()

        enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_tool.id,
            AIWebDetailToolsModel.tool_type == 2,
            AIWebDetailToolsModel.is_enabled == True
        ).count()

        # 返回响应
        result_dict = mcp_tool.to_dict()
        result_dict['tools_count'] = tools_count
        result_dict['enabled_tools_count'] = enabled_tools_count
        result_dict['status_display'] = mcp_tool.get_status_display()
        result_dict['access_type_display'] = mcp_tool.get_access_type_display()

        return AIWebMCPToolsResponse(**result_dict)

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取MCP工具详情失败: {str(e)}")


# =========================== MCP工具详情管理 ===========================

@router.get("/{mcp_id}/tools", response_model=AIWebDetailToolsListResponse, summary="获取MCP工具下的详情工具列表")
async def get_mcp_detail_tools(
        mcp_id: str,
        db: Session = Depends(get_db_session)
):
    """获取MCP工具下的详情工具列表"""
    try:
        # 验证MCP工具是否存在
        mcp_tool = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.id == mcp_id
        ).first()

        if not mcp_tool:
            raise HTTPException(status_code=404, detail="MCP工具不存在")

        # 查询工具详情 - 只查询MCP工具(tool_type=2)
        tools = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.parent_id == mcp_id,
            AIWebDetailToolsModel.tool_type == 2
        ).order_by(AIWebDetailToolsModel.created_at.desc()).all()

        # 转换为响应模型
        response_items = [AIWebDetailToolsResponse(**tool.to_dict()) for tool in tools]

        return AIWebDetailToolsListResponse(total=len(response_items), items=response_items)

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具详情列表失败: {str(e)}")


@router.put("/{mcp_id}/tools/{tool_id}", response_model=AIWebDetailToolsResponse, summary="更新MCP工具详情")
async def update_mcp_detail_tool(
        mcp_id: str,
        tool_id: int,
        tool_data: AIWebDetailToolsUpdate,
        db: Session = Depends(get_db_session)
):
    """更新MCP工具详情"""
    try:
        # 查找工具详情 - 只查询MCP工具(tool_type=2)
        detail_tool = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.id == tool_id,
            AIWebDetailToolsModel.parent_id == mcp_id,
            AIWebDetailToolsModel.tool_type == 2
        ).first()

        if not detail_tool:
            raise HTTPException(status_code=404, detail="工具详情不存在")

        # 检查工具名称重复（排除自身） - 只在MCP工具中检查(tool_type=2)
        if tool_data.tool_name:
            existing = db.query(AIWebDetailToolsModel).filter(
                AIWebDetailToolsModel.parent_id == mcp_id,
                AIWebDetailToolsModel.tool_name == tool_data.tool_name,
                AIWebDetailToolsModel.tool_type == 2,
                AIWebDetailToolsModel.id != tool_id
            ).first()

            if existing:
                raise HTTPException(status_code=400, detail="该MCP工具下已存在同名工具")

        # 更新字段
        update_data = tool_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            if field == 'parameters':
                detail_tool.set_parameters(value)
            else:
                setattr(detail_tool, field, value)

        db.commit()
        db.refresh(detail_tool)

        return AIWebDetailToolsResponse(**detail_tool.to_dict())

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具详情失败: {str(e)}")


@router.delete("/{mcp_id}/tools/{tool_id}", summary="删除MCP工具详情")
async def delete_mcp_detail_tool(
        mcp_id: str,
        tool_id: int,
        db: Session = Depends(get_db_session)
):
    """删除MCP工具详情"""
    try:
        # 查找工具详情 - 只查询MCP工具(tool_type=2)
        detail_tool = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.id == tool_id,
            AIWebDetailToolsModel.parent_id == mcp_id,
            AIWebDetailToolsModel.tool_type == 2
        ).first()

        if not detail_tool:
            raise HTTPException(status_code=404, detail="工具详情不存在")

        # 删除工具详情
        db.delete(detail_tool)
        db.commit()

        return {"message": "工具详情删除成功"}

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除工具详情失败: {str(e)}")


@router.put("/{mcp_id}/tools/{tool_id}/status", response_model=AIWebDetailToolsResponse, summary="更新MCP工具详情状态")
async def update_mcp_detail_tool_status(
        mcp_id: str,
        tool_id: int,
        status_data: AIWebDetailToolsStatusUpdate,
        db: Session = Depends(get_db_session)
):
    """更新MCP工具详情状态"""
    try:
        # 查找工具详情 - 只查询MCP工具(tool_type=2)
        detail_tool = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.id == tool_id,
            AIWebDetailToolsModel.parent_id == mcp_id,
            AIWebDetailToolsModel.tool_type == 2
        ).first()

        if not detail_tool:
            raise HTTPException(status_code=404, detail="工具详情不存在")

        # 更新状态
        detail_tool.is_enabled = status_data.is_enabled
        db.commit()
        db.refresh(detail_tool)

        return AIWebDetailToolsResponse(**detail_tool.to_dict())

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具详情状态失败: {str(e)}")


@router.put("/{mcp_id}/tools/{tool_id}/interactive", response_model=AIWebDetailToolsResponse,
            summary="更新MCP工具详情人工交互标识")
async def update_mcp_detail_tool_interactive(
        mcp_id: str,
        tool_id: int,
        interactive_data: AIWebDetailToolsInteractiveUpdate,
        db: Session = Depends(get_db_session)
):
    """更新MCP工具详情人工交互标识"""
    try:
        # 查找工具详情 - 只查询MCP工具(tool_type=2)
        detail_tool = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.id == tool_id,
            AIWebDetailToolsModel.parent_id == mcp_id,
            AIWebDetailToolsModel.tool_type == 2
        ).first()

        if not detail_tool:
            raise HTTPException(status_code=404, detail="工具详情不存在")

        # 更新人工交互标识
        detail_tool.update_human_interactive_flag(interactive_data.human_interactive_flag)
        db.commit()
        db.refresh(detail_tool)

        return AIWebDetailToolsResponse(**detail_tool.to_dict())

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新工具人工交互标识失败: {str(e)}")


# =========================== 辅助接口 ===========================

@router.get("/options/status", summary="获取状态选项")
async def get_status_options():
    """获取状态选项"""
    return AIWebMCPToolsModel.get_all_status_options()


@router.get("/options/access-type", summary="获取接入类型选项")
async def get_access_type_options():
    """获取接入类型选项"""
    return AIWebMCPToolsModel.get_all_access_type_options()


@router.get("/connected-servers", summary="获取已连接的MCP服务器")
async def get_connected_servers():
    """获取已连接的MCP服务器列表"""
    try:
        servers = mcp_manager.get_connected_servers()
        return {
            "connected_servers": servers,
            "count": len(servers)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取连接状态失败: {str(e)}")


@router.get("/stats", summary="获取MCP工具统计信息")
async def get_mcp_stats(db: Session = Depends(get_db_session)):
    """获取MCP工具统计信息"""
    try:
        # 总数
        total_count = db.query(AIWebMCPToolsModel).count()

        # 各状态数量
        testing_count = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.status == 0
        ).count()

        online_count = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.status == 1
        ).count()

        discontinued_count = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.status == 2
        ).count()

        # 各接入类型数量
        api_count = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.access_type == 1
        ).count()

        local_tool_count = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.access_type == 2
        ).count()

        # 工具详情统计 - 只统计MCP工具(tool_type=2)
        total_tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.tool_type == 2
        ).count()

        enabled_tools_count = db.query(AIWebDetailToolsModel).filter(
            AIWebDetailToolsModel.tool_type == 2,
            AIWebDetailToolsModel.is_enabled == True
        ).count()

        # 已连接的服务器数量
        connected_servers = mcp_manager.get_connected_servers()

        return {
            "total_count": total_count,
            "testing_count": testing_count,
            "online_count": online_count,
            "discontinued_count": discontinued_count,
            "api_count": api_count,
            "local_tool_count": local_tool_count,
            "total_tools_count": total_tools_count,
            "enabled_tools_count": enabled_tools_count,
            "connected_servers_count": len(connected_servers),
            "connected_servers": connected_servers
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")
